import logging
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView


from QQLoginTool.QQtool import OAuthQQ


from oauth.models import OAuthQQUser
from oauth.serializers import OAuthUserSerializer
from oauth.utils import generate_save_user_token
from carts.utils import merge_cart_cookie_to_redis

logger  = logging.getLogger('django')

# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(GenericAPIView):

    """OAuth2.0认证：获取openid及判断是否绑定用户"""
    def get(self, request):

        #1.获取前端传过来的code
        try:
            code = request.query_params.get('code')
        except:
            return Response({'message':'code不可用'},status=status.HTTP_400_BAD_REQUEST)
        #2.创建oauthqq对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                            client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI,
                            state=next)

        try:
            # 3.拿code向qq服务器后去access_token
            access_token = oauth.get_access_token(code)
            # 4.拿access_token获取openid
            openid = oauth.get_open_id(access_token)
        except Exception as error:
            logger.info(error)
            return Response({'message':'QQ服务不可用'})

        try:
        #再用openid去查询有没有绑定过用户
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
        #如果openid没有绑定过用户？？
            access_token_openid = generate_save_user_token(openid)
            return Response({'access_token':access_token_openid})

        else:
            # 如果openid定过用户？？
            #获取openid绑定过的用户
            user = oauth_user.user
            #生成jwt_token并返回
            jwt_payload_headler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_headler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_headler(user)
            token = jwt_encode_headler(payload)

            response = Response({
                'token':token,
                'user_id': user.id,
                'user_name': user.username
            })


            response = merge_cart_cookie_to_redis(request, user, response)

            return response

    def post(self, request):
        """用户绑定openid"""
        # 创建序列化器
        serializer = OAuthUserSerializer(data=request.data)
        #校验
        serializer.is_valid(raise_exception=True)
        #保存到数据库
        user = serializer.save()

        # 生成jwt_token并返回
        jwt_payload_headler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_headler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_headler(user)
        token = jwt_encode_headler(payload)

        return Response({
            'token': token,
            'user_id': user.id,
            'user_name': user.username
        })


# url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):

    """此视图用来返回给前端qq扫码登录后返回的界面url"""

    def get(self,request):

        next = request.query_params.get('next')

        if not next:

            next = '/'

        #获取qq登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        login_url = oauth.get_qq_url()

        return Response({'login_url':login_url})

